package com.system.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
            throws IOException, ServletException {
        System.out.println("进来LoginFilter了");
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;
        HttpSession session = request.getSession();
//        System.out.println(request.getContextPath());
        //如果请求的是/sysUser/login,/,/login.html则通过
		String requestURI = requestUriHandler(request.getRequestURI());
		if (requestURI.equals("/sysUser/login") || requestURI.equals("/") || requestURI.equals("/login.html")){
			System.out.println("放行了");
			arg2.doFilter(request, response);
		}else{
			Object user = session.getAttribute("sysUser");
			if (user == null){
				System.out.println("转发到登陆页面");
				request.getRequestDispatcher("/login.html")
						.forward(request, response);
				return;
			}else{
                System.out.println("放行了");
                arg2.doFilter(request, response);
            }
		}

    }

    public String requestUriHandler(String uri) {
        String substring = uri.substring(1);
        String substring1 = substring.substring(substring.indexOf("/"));
        System.out.println(substring1);
        return substring1;
    }

}
